//
//  JBeautifulViewController.m
//  HeadIndustry
//
//  Created by jun on 2017/8/24.
//  Copyright © 2017年 jun. All rights reserved.
//

#import "JBeautifulViewController.h"
#import "JFriendCircleController.h" // 圈聊
#import "JCreateActivityController.h" // 创建活动
#import "JKeepRecordController.h" // 写日记
@interface JBeautifulViewController ()<WKNavigationDelegate, WKScriptMessageHandler, WKUIDelegate>

@property (nonatomic, strong) WKWebView *webView;

@end

@implementation JBeautifulViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.tabBarController.tabBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [super InitUI];
    self.view.backgroundColor = [UIColor whiteColor];
    [self creatWebView];

}

- (void)creatWebView {
    WKWebViewConfiguration *config = [WKWebViewConfiguration new];
    config.preferences = [WKPreferences new];
    config.preferences.minimumFontSize = 10;
    config.preferences.javaScriptEnabled = YES;
    config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
    config.userContentController = [WKUserContentController new];
    [config.userContentController addScriptMessageHandler:self name:html_name];
    
    _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 20, kWindowW, kWindowH-20) configuration:config];
    
    NSDictionary *dic = @{@"CustomerId":@([GLOBALDATA userInfoModel].CustomerId),
                          @"UserId":@([GLOBALDATA userInfoModel].CustomerId),
                          @"Page":@(1),
                          @"PageSize":@(10)};
    
    NSString *urlStrBody = [self convertToJsonData:dic];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:Beautiful_HTML_URL_STR]];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[urlStrBody dataUsingEncoding:NSUTF8StringEncoding]];
    
    [_webView loadRequest:request];
    [self.view addSubview:_webView];
    [self.view bringSubviewToFront:_webView];
    _webView.navigationDelegate = self;
    _webView.UIDelegate = self;
}

#pragma mark = WKNavigationDelegate
//在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    [SVProgressHUD dismiss];
    
    NSString *hostname = navigationAction.request.URL.host.lowercaseString;
    
//    NSLog(@"hostname====%@",hostname);
    
    NSURL *hostURL = navigationAction.request.URL;
//    NSLog(@"hostname====%@",[hostURL absoluteString]);
    NSString *urlStr = [hostURL absoluteString];
    
    // 进入圈聊
    if ([urlStr isEqualToString:BuildCircle]) {
        decisionHandler(WKNavigationActionPolicyCancel);
        JFriendCircleController *friendVC = [[JFriendCircleController alloc]init];
        friendVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:friendVC animated:YES];
        

    }
    
    else if ([urlStr isEqualToString:ActivityBuild]) {
        decisionHandler(WKNavigationActionPolicyCancel);
        JCreateActivityController *friendVC = [[JCreateActivityController alloc]init];
        friendVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:friendVC animated:YES];
        
    }
    
    else if ([urlStr isEqualToString:WriteDiary]) {
        decisionHandler(WKNavigationActionPolicyCancel);
        JKeepRecordController *friendVC = [[JKeepRecordController alloc]init];
        friendVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:friendVC animated:YES];
        
    }
    
    else if (navigationAction.navigationType == WKNavigationTypeLinkActivated
        && ![hostname containsString:@".touhanggo.com"]) {
        // 对于跨域，需要手动跳转
        [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
        
        // 不允许web内跳转
        decisionHandler(WKNavigationActionPolicyCancel);
    } else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
    
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    if ([message.name isEqualToString:html_name]) {
        if ([message.body isKindOfClass:[NSString class]]) {
            if ([message.body isEqualToString:goback_beautiful]) { // 退出美丽圈
//                [self.navigationController popViewControllerAnimated:YES];
                
                UIWindow *window = [[[UIApplication sharedApplication] delegate ] window];\
                UITabBarController *table = (UITabBarController *)window.rootViewController;\
                table.selectedIndex = 0;
                
            }
            
        }
    }
}


- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    [SVProgressHUD show];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [SVProgressHUD dismiss];
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    [SVProgressHUD showErrorWithStatus:@"加载失败"];
}

//在响应完成时，调用的方法。如果设置为不允许响应，web内容就不会传过来
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    decisionHandler(WKNavigationResponsePolicyAllow);



}
//接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{

}


// 字典转json字符串方法

-(NSString *)convertToJsonData:(NSDictionary *)dict

{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
